package com.demo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.scene.control.Label;
import javafx.concurrent.Worker.State;

import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

// 定义一个接口来接收回调
interface TagContentCallback {
    void onTagContentReceived(String elementContent);
}

public class WebViewCursorPositionExample extends Application {

    private static final Logger logger = Logger.getLogger(WebViewCursorPositionExample.class.getName());
    private static TagContentCallback callback;

    @Override
    public void start(Stage primaryStage) {
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();

        // 加载HTML内容
        String htmlContent = "<h1 contenteditable='true'>Header 1</h1>\n" +
                "<h2 contenteditable='true'>Header 2</h2>\n" +
                "<h3 contenteditable='true'>Header 3</h3>\n" +
                "<blockquote contenteditable='true'><p contenteditable='true'>引用</p></blockquote>";

        webEngine.loadContent(htmlContent);

        Label cursorPositionLabel = new Label("光标位置: ");

        // 监听键盘事件
        webView.setOnKeyPressed(event -> {
            if (event.getCode().isLetterKey() || event.getCode().isDigitKey()) {
                // 当用户输入字符时，获取光标位置
                getCursorPosition(webEngine, cursorPositionLabel);
            }
        });

        // 设置回调
        setJavaScriptCallback(webEngine, cursorPositionLabel);

        VBox root = new VBox(webView, cursorPositionLabel);
        Scene scene = new Scene(root, 800, 600);

        primaryStage.setTitle("WebView Cursor Position Example");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void getCursorPosition(WebEngine webEngine, Label cursorPositionLabel) {
        // 使用JavaScript获取光标位置
        CompletableFuture<String> future = (CompletableFuture<String>) webEngine.executeScript(
                "var selection = window.getSelection();"
                        + "if (selection.rangeCount > 0) {"
                        + "  var range = selection.getRangeAt(0);"
                        + "  var element = range.startContainer.parentNode;"
                        + "  var elementContent = element.outerHTML;"
                        + "  window.javaScriptCallback(elementContent);"
                        + "} else {"
                        + "  window.javaScriptCallback('');"
                        + "}"
        );

        future.thenAccept((elementContent) -> {
            cursorPositionLabel.setText("光标位置: " + elementContent);
        }).exceptionally(ex -> {
            cursorPositionLabel.setText("光标位置: 错误");
            logger.log(Level.SEVERE, "Error getting cursor position", ex);
            return null;
        });
    }

    private void setJavaScriptCallback(WebEngine webEngine, final Label cursorPositionLabel) {
        // 定义JavaScript回调函数
        webEngine.executeScript("window.javaScriptCallback = function(elementContent) {"
                + "  var callback = Java.type('com.example.WebViewCursorPositionExample').callback;"
                + "  if (callback) {"
                + "    callback.onTagContentReceived(elementContent);"
                + "  }"
                + "}");

        // 在页面加载完成后重新定义回调函数
        webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == State.SUCCEEDED) {
                webEngine.executeScript("window.javaScriptCallback = function(elementContent) {"
                        + "  var callback = Java.type('com.example.WebViewCursorPositionExample').callback;"
                        + "  if (callback) {"
                        + "    callback.onTagContentReceived(elementContent);"
                        + "  }"
                        + "}");
            }
        });

        // 设置回调
        WebViewCursorPositionExample.callback = (String elementContent) -> {
            cursorPositionLabel.setText("光标位置: " + elementContent);
        };
    }

    public static void main(String[] args) {
        launch(args);
    }
}